function sortChar(a, b){
  return a.y - b.y;
}
    
var socket;
var charsMap = {};
var charsArray = [];
var mychar = {};
var cursor = {
  x:0,
  y:0
};
var focusChar = null;
var hasFocus = false;
var dist = 0;

$(document).ready(function(){
   
  var canvas = document.getElementById('screen');
  var stage = new Stage(canvas);

  stage.addScene({
    init : function() {
    },
    update : function(delta) {
            
      var forRemove = [];
      for (var x = 0, xln = charsArray.length; x < xln; x++) {
        if(!charsArray[x].active && !charsArray[x].visible){
          forRemove.push(x);
        }
      }
                  
      for (var r = 0, rln = forRemove.length; r < rln; r++) {
        charsArray.remove(forRemove[r]);
      }
            
      hasFocus = false;
      for (var i = 0, iln = charsArray.length; i < iln; i++) {
        var dchar = charsArray[i];
        dchar.focus = false;
        if(dchar !== mychar){
          if(!hasFocus){
            if(dchar.active && (Math.abs(dchar.x - cursor.x) + Math.abs(dchar.y - cursor.y)) < 15){
              dchar.focus = true;
              focusChar = dchar;
              hasFocus = true;
            }
          }
        }
                
                
        dchar.update(delta);
      }
            
      if(!hasFocus){
        focusChar = null;
      }else{
        dist = Math.abs(mychar.x - focusChar.x) + Math.abs(mychar.y - focusChar.y);
      }
            
      charsArray.sort(sortChar);
    },
    render : function(ctx) {
            
      ctx.translate(GAME_HALF_WIDTH - mychar.x , GAME_HALF_HEIGHT - mychar.y);
      ctx.beginPath();
      ctx.moveTo(0,0);
      ctx.lineTo(0,GAME_HEIGHT);
      ctx.lineTo(GAME_WIDTH,GAME_HEIGHT);
      ctx.lineTo(GAME_WIDTH,0);
      ctx.closePath();
      ctx.stroke();
            
      for (var i = 0, ln = charsArray.length; i < ln; i++) {
        charsArray[i].render(ctx);
      }
           
    },
    click : function(x, y){
      if(mychar.active){
        var cx = x - (GAME_HALF_WIDTH - mychar.x);
        var cy = y - (GAME_HALF_HEIGHT - mychar.y);
            
        if(focusChar && (Math.abs(mychar.x - focusChar.x) + Math.abs(mychar.y - focusChar.y)) < 30.0){
          socket.emit('atk',focusChar.id);
        }else{   
          if(cx >= 0 && cy >= 0 && cx <= GAME_WIDTH && cy  <= GAME_HEIGHT){
            socket.emit('move', {
              x:cx, 
              y:cy
            });  
          }
        }
        cursor.x = -1;
        cursor.y = -1;
      }
    },
    mousemove: function(x, y){
      cursor.x = x - (GAME_HALF_WIDTH - mychar.x);
      cursor.y = y - (GAME_HALF_HEIGHT - mychar.y);
    },
    keyup: function(e){

    },
    keydown: function(e){

    }
  });
    
  stage.setCurrentScene(0);
    
  socket = io.connect('http://localhost:3366');
  //  socket = io.connect('http://192.168.2.30:3366');  
  var sid = document.cookie;
  sid = sid.substr(sid.indexOf("=") + 1, sid.length);

  socket.emit('join', decodeURIComponent(sid));
  socket.on('newchar', function (data) {
    var id = data.id;
    var dChar = new_warrior(id, data.x, data.y, data.name);
    charsMap[id] = dChar;
    charsArray.push(dChar);
    socket.on(id, function(data){
      switch(data.cmd){
        case 'move':
          charsMap[id].moveTo(data.x, data.y);
          break;
        case 'die':
          charsMap[id].attack(charsMap[data.id]);
          charsMap[data.id].die();
          break;
      }
    });
  });
        
  socket.on('mychar', function(data){
    var id = data.id;
    mychar = new_warrior(id, data.x, data.y, data.name);
    charsMap[id] = mychar;
    charsArray.push(mychar);
    socket.on(id, function(data){
      switch(data.cmd){
        case 'move':
          charsMap[id].moveTo(data.x, data.y);
          break;
        case 'die':
          charsMap[id].attack(charsMap[data.id]);
          charsMap[data.id].die();
          break;
      }
    });
    stage.start();
  });
    
  socket.on('delchar', function(data){
    for (var i = 0, ln = charsArray.length; i < ln; i++) {
      if(charsArray[i].name === charsMap[data].name){
        charsArray.remove(i);
        break;
      }
    }
    delete charsMap[data];
  });
  
  socket.on('scores', function(score){
    
    if($('#' + score.name).length){
      $('#' + score.name).html(score.name + " kills:" + score.kills + " deaths:" + score.deaths );
    }else{
      $('#scores').append("<div id='" + score.name +"'>" + score.name + " kills:" + score.kills + " deaths:" + score.deaths  + "</div>");
    }
    if($('#' + score.name2).length){
      $('#' + score.name2).html(score.name2 + " kills:" + score.kills2 + " deaths:" + score.deaths2 );
    }else{
      $('#scores').append("<div id='" + score.name2 +"'>" + score.name2 + " kills:" + score.kills2 + " deaths:" + score.deaths2  + "</div>");
    }
  });
     
     
  socket.on('mesg', function(mesg){
      alert(mesg);
  });
});
